<template>
  <div class="container">
    <div
      class="row no-gutters bg-light position-relative mb-4 shadow p-3 mb-5 bg-white rounded"
      v-bind:key="blog.BlogId"
      v-for="blog in blogs"
    >
      <div class="col-md-6 mb-md-0 p-md-4">
        <img
          style="width: 100%"
          :src="VUE_APP_CoverImage + blog.Cover"
          class="w-70"
          alt="图片错误"
        />
      </div>
      <div class="col-md-6 p-4 pl-md-0">
        <h5 class="mt-0">{{ blog.Title }}</h5>
        <h6>{{ blog.UpdateTime }}</h6>
        <p>{{ blog.Introduction }}</p>
        <div class="buttons">
          <span @click="editBlog(blog)" class="btn btn-primary" to="#"
            >编辑</span
          >&nbsp;&nbsp;&nbsp;&nbsp;
          <span @click="deleteBlog(blog, index)" class="btn btn-danger"
            >删除</span
          >
        </div>
      </div>
    </div>
    <MoPaging
      @change="pageChange"
      v-bind:totalPage="pagination.totalPage"
      v-bind:currentPage="pagination.currentPage"
    />
    <Prompt ref="prompt"></Prompt>
  </div>
</template>

<script>
import axios from "axios";
import MoPaging from "../MoPaging";
import Prompt from "../Prompt";
import { create } from "domain";

export default {
  name: "List",
  data() {
    return {
      blogs: [],
      pagination: Object,
      VUE_APP_CoverImage:''
    };
  },
  components: {
    MoPaging,
    Prompt,
  },
  methods: {
    // 删除
    deleteBlog(blog, index) {
      window.console.log(blog.BlogId);
      axios
        .delete("/api/Blog/" + blog.BlogId)
        .then((res) => {
          this.blogs.splice(index, 1);
          this.$refs.prompt.alertDia("删除成功");
        })
        .catch((err) => {
          // window.console.log(err.response);
          if (err.response.status == "401") {
            //如果返回码位401 则说明登录失效 退出登录
            sessionStorage.removeItem("token");
          }
        });
    },
    editBlog(blog) {
      this.$parent.Edit(blog);
    },
    //获取数据
    getList() {
      axios
        .get("/api/Blog?PageNumber=" + this.pagination.currentPage)
        .then((res) => (this.blogs = res.data))
        .catch((err) => window.console.log(err));
    },
    //从page组件传递过来的当前page
    pageChange(currentPage) {
      // window.console.log(currentPage);
      this.pagination.currentPage = currentPage;
      this.getList();
    },
  },
  mounted(){
    this.VUE_APP_CoverImage = process.env.VUE_APP_CoverImage;
  },
  created() {
    axios
      .get("/api/Blog")
      .then((res) => {
        this.blogs = res.data;
        this.pagination = JSON.parse(res.headers.pagination);
        // window.console.log(JSON.parse(res.headers.pagination));
      })
      .catch((err) => window.console.log(err));
  },
};
</script>

<style scoped>
.container {
  padding-top: 20px;
}
.card {
  margin: 20px 0;
}
.buttons {
  bottom: 24px;
  position: absolute;
}
</style>
